class Particle {
  constructor(x, y, hue) {
    // 初始位置
    this.x = x
    this.y = y

    // 从烟花那得来的hsla色调
    this.hue = this._getRandomRange(hue - 20, hue + 20)
    //this.hue = hue
    // 随机hsla亮度
    this.lightness = this._getRandomRange(50, 80)

    // 初始透明度
    this.alpha = 1
    // 随机的透明度衰变系数（透明度减淡）
    this.alphaDecay = this._getRandomRange(0.015, 0.03)

    // 模拟下坠摩擦力(让粒子减速)
    this.friction = 0.95
    // 模拟重力加速度
    this.gravity = 1

    // 随机角度
    this.angle = this._getRandomRange(0, 2 * Math.PI)
    // 随机初始速度
    this.speed = this._getRandomRange(1, 10)
  }

  draw(ctx) {
    ctx.save()
    // 减速
    this.speed *= this.friction
    // 计算新位置
    const moveX = this.x + Math.cos(this.angle) * this.speed
    const moveY = this.y + Math.sin(this.angle) * this.speed + this.gravity

    ctx.beginPath()
    ctx.moveTo(this.x, this.y)
    ctx.lineTo(moveX, moveY)

    ctx.strokeStyle = `hsla(${this.hue}, 100%, ${this.lightness}%, ${this.alpha})`
    ctx.lineWidth = 3
    ctx.lineCap = 'round'
    ctx.stroke()
    ctx.restore()
    this.x = moveX
    this.y = moveY
    // 透明度衰减
    this.alpha -= this.alphaDecay
  }

  _getRandomRange(min, max) {
    return Math.random() * (max - min) + min
  }

  // 粒子是否已经看不见
  isVanished() {
    return this.alpha < this.alphaDecay
  }
}
